import json

from django.core.exceptions import ObjectDoesNotExist
from langchain_community.llms import Tongyi
from langchain_core.prompts import ChatPromptTemplate
from langchain.agents import Tool, AgentExecutor, create_react_agent, tool, AgentType, initialize_agent
from langchain_community.embeddings import DashScopeEmbeddings
from langchain_chroma import Chroma
from rest_framework.response import Response
from rest_framework.views import APIView

from dkeep import settings
from django.core.mail import send_mail

from keep.models import Task, Approval_Record, WorkflowApprovalNode
from keep.models import Workflow,StaffModel
from keep.seriali import TaskSerializer

# def send_email_cd(mail):
#     subject = "测试发送邮箱主题"
#     message = "测试发送邮箱内容"
#     from_email = settings.EMAIL_FROM
#     to_email = [mail]
#     send_status = send_mail(subject, message, from_email, to_email)
#     print(send_status)
#     return send_status
# class SendEmailView(APIView):
#     def get(self,request):
#         send_email_cd("xr19020024044@163.com")
#         return Response({"message":"发送成功"})
# 添加任务
llm=Tongyi()
def add_task(input):
        # 创建Task实例，将数据填入任务表
        task = json.loads(input)
        Task_exist=Task.objects.filter(workflow_id=task["workflow_id"], staffid=task["staffid"]).first()
        if Task_exist and Task_exist.task_status==0:
            return {"message":"任务已存在,请勿重复添加"}
        else:
            add_task=Task.objects.create(
                name=task["name"],
                params=task["params"],
                workflow_id=Workflow.objects.get(id=task["workflow_id"]),
                staffid=StaffModel.objects.get(id=task["staffid"]),
                next_audit=StaffModel.objects.get(id=task["next_audit"]),
                level=task["level"],
                task_status=0,
            )
            # 返回新创建的任务的ID
            return str(add_task.id)
#分配审批人
def set_audit(input):
    task = json.loads(input)
    data = Task.objects.filter(next_audit=task["next_audit"]).all()
    print(data)
    ser = TaskSerializer(data, many=True)
    return ser.data
#
# 更新审批结果
def audit_agree(input):
    task = json.loads(input)
    task_id = task['task_id']
    is_agree = task['is_agree']
    audit_user = int(task['audit_user'])
    tasks = Task.objects.get(id=task_id)
    workflow_id = tasks.workflow_id.id
    level = tasks.level
    print(workflow_id, level)
    print("++++++++++++++==============++++++++++++++")
    if int(is_agree) == 1:
        # 同意
        # 加入审批记录表
        Approval_Record.objects.create(
            task_id=Task.objects.get(id=task_id),
            audit_user=StaffModel.objects.get(id=audit_user),
            audit_status='approved'  # 已审批
        )
        # 查询审批节点表
        pot = WorkflowApprovalNode.objects.filter(workflow_id=workflow_id, level__gt=level).order_by(
            'level').first()
        print('------------', pot)
        # 有下一审批人
        if pot:
            next_audit_position = pot.position_id  # 拿到下一审批人的职位
            print(next_audit_position)
            next_audit_department = pot.position_id.department  # 拿到下一审批人的部门
            print(next_audit_department)
            next_audit = StaffModel.objects.filter(position=next_audit_position, dept_id=
            next_audit_department).first()
            # next_audit_id = StaffSerializer(next_audit)["id"]
            next_audit_id = next_audit.id
            # 任务表
            new_task = Task.objects.filter(workflow_id=workflow_id).update(
                next_audit=next_audit_id,
                level=pot.level,
            )
            return "下一审批人:"+next_audit.name+"审批"
        else:
            # 没有下一审批人
            new_task = Task.objects.filter(workflow_id=workflow_id).update(
                task_status=1
            )
            return  "审批完成"
    elif int(is_agree) == 2:
        # 不同意
        if level == 1:
            Approval_Record.objects.create(
                task_id=Task.objects.get(id=task_id),
                audit_user=StaffModel.objects.get(id=audit_user),
                audit_status='rejected'  # 已拒绝
            )
            # 第一个审批人拒绝，任务状态修改为已退回，请重新申请
            Task.objects.filter(id=task_id, workflow_id=workflow_id).update(
                task_status=2
            )
            return  "第一个审批人审批不通过"
        else:
            # 查询审批节点表
            pot = WorkflowApprovalNode.objects.filter(id=task_id, workflow_id=workflow_id, level__lt=level).order_by(
                '-level').first()
            next_audit_position = pot.position_id  # 拿到下一审批人的职位
            next_audit_department = pot.position_id.department  # 拿到下一审批人的部门
            next_audit = StaffModel.objects.filter(position=next_audit_position, dept_id=
            next_audit_department).first()
            next_audit_id = next_audit.id
            print("================")
            print("pot.level", pot.level)
            # 任务表
            new_task = Task.objects.filter(id=task_id, workflow_id=workflow_id).update(
                next_audit=next_audit_id,
                level=pot.level,
            )
            # 加入审批记录表
            Approval_Record.objects.create(
                task_id=Task.objects.get(id=task_id),
                audit_user=StaffModel.objects.get(id=audit_user),
                audit_status='rejected'  # 已拒绝
            )
            return "审批不通过，已退回至上一审批人"+next_audit.name


def audit_workflow(input):
    tools = [
        Tool(name="add_task", func=add_task,
             description="当用户提交任务用这个工具回答，把参数转成json传入到工具,只返回一个任务id的数字，例如9，不要返回其他的信息"),
        Tool(name="set_audit", func=set_audit,
             description="分配审批人,任务提交成功后时使用这个工具回答，只返回一个下一个审批人id的数字，例如9，不要返回其他的信息,如果要返回包含任务id和下一个审批人id的字典，请保持下一审批人id的键是next_audit"),
        Tool(name="audit_agree", func=audit_agree,
             description="更新审核结果，审批人审批过后返回结果并更新数据时使用这个工具回答"),
    ]
    agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
    res = agent.invoke(input)
    print(res)
    return res